package com.song.su.controller;

import com.song.su.mapper.CommentMapper;
import com.song.su.model.CommentUser;
import com.song.su.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;

@Controller
public class CommentController {

    private String book_id;
    @Autowired
    CommentMapper commentMapper;

    @GetMapping("/comment")
    public String publish(@RequestParam(name="bookid") String bookid
    ){
        book_id = bookid;
        return "comment";
    }

    @RequestMapping(value = "/comment", method = {RequestMethod.POST})
    public String doPublish(
            @RequestParam(name="title") String title,
            @RequestParam(name="context") String context,
                    HttpServletRequest request,
                    Model model
    ){
        model.addAttribute("title",title);
        model.addAttribute("context",context);
        if (StringUtils.isBlank(title)) {
            model.addAttribute("error", "标题不能为空");
            return "comment";
        }
        if (StringUtils.isBlank(context)) {
            model.addAttribute("error", "标题不能为空");
            return "comment";
        }


        User user = (User) request.getSession().getAttribute("user");
        if(user == null){
            model.addAttribute("error","用户未登陆");
            return "comment";
        }
        CommentUser commentUser = new CommentUser();
        commentUser.setAccount_Id(user.getAccountId());
        System.out.println(user.getAccountId());
        commentUser.setAccountName(user.getName());
        commentUser.setComContext(context);
        commentUser.setComTitle(title);
        commentUser.setGmtCreate(System.currentTimeMillis());
        commentUser.setGmtModified(commentUser.getGmtCreate());
        commentUser.setBookId(book_id);
        commentMapper.create(commentUser);
        return "redirect:/book?isbn="+book_id;

    }

}
